#!/bin/sh

IBPATH=${IBPATH:-@IBSCRIPTPATH@}

usage() {
	echo Usage: `basename $0` "[-h] [-v] [-N | -nocolor]" \
	    "[<topology-file> | -C ca_name -P ca_port -t(imeout) timeout_ms]"
	exit 255
}

user_abort() {
	echo "Aborted"
	exit 1
}

trap user_abort SIGINT

gflags=""
verbose=""
v=0
oldlid=""
topofile=""
ca_info=""

while [ "$1" ]; do
	case $1 in
	-h)
		usage
		;;
	-N|-nocolor)
		gflags=-N
		;;
	-v)
		verbose=-v
		v=0
		;;
	-P | -C | -t | -timeout)
		case $2 in
		-*)
			usage
			;;
		esac
		if [ x$2 = x ] ; then
			usage
		fi
		ca_info="$ca_info $1 $2"
		shift
		;;
	-*)
		usage
		;;
	*)
		if [ "$topofile" ]; then
			usage
		fi
		topofile="$1"
		;;
	esac
	shift
done

if [ "$topofile" ]; then
	netcmd="cat $topofile"
else
	netcmd="$IBPATH/ibnetdiscover $ca_info"
fi

text="`eval $netcmd`"
rv=$?
echo "$text" | awk '
BEGIN {
	ne=0
	pe=0
}
function check_node(lid, port)
{
	if (system("'$IBPATH'/ibchecknode -S '"$ca_info"' '$gflags' '$verbose' " lid)) {
		ne++
		print "\n# " ntype ": nodeguid 0x" nodeguid " failed"
		return 1;
	}
	if (system("'$IBPATH'/ibcheckerrs -S '"$ca_info"' '$gflags' '$verbose' '$brief' " lid " " port))
		return  2;
	return 0;
}

/^Ca/ || /^Switch/ || /^Rt/ {
			nnodes++
			ntype=$1; nodeguid=substr($3, 4, 16); ports=$2
			if ('$v' || ntype != "Switch")
				print "\n# Checking " ntype ": nodeguid 0x" nodeguid

			err = 0;
			if (ntype != "Switch")
				next

			lid = substr($0, index($0, "port 0 lid ") + 11)
			lid = substr(lid, 1, index(lid, " ") - 1)
			err = check_node(lid, 255)
		}
/^\[/	{
		nports++
		port = $1
		sub("\\(.*\\)", "", port)
		gsub("[\\[\\]]", "", port)
		if (ntype != "Switch") {
			lid = substr($0, index($0, " lid ") + 5)
			lid = substr(lid, 1, index(lid, " ") - 1)
			if (check_node(lid, port) == 2)
  				pcnterr++;
		} else if (err &&
			   system("'$IBPATH'/ibcheckerrs -S '"$ca_info"' '$gflags' '$verbose' '$brief' " lid " " port))
			pcnterr++;
		if (system("'$IBPATH'/ibcheckport -S '"$ca_info"' '$gflags' '$verbose' " lid " " port)) {
			if (!'$v' && oldlid != lid) {
				print "# Checked " ntype ": nodeguid 0x" nodeguid " with failure"
				oldlid = lid
			}
			pe++;
		}
}

/^ib/	{print $0; next}
/ibpanic:/	{print $0}
/ibwarn:/	{print $0}
/iberror:/	{print $0}

END {
	printf "\n*** WARNING ***: this command is deprecated; Please use \"ibqueryerrors\""
	printf "\n## Summary: %d nodes checked, %d bad nodes found\n", nnodes, ne
	printf "##          %d ports checked, %d bad ports found\n", nports, pe
	printf "##          %d ports have errors beyond threshold\n", pcnterr
	exit (ne + pe + pcnterr)
}
'
av=$?
if [ $av -ne 0 ] ; then
	exit $av
else
	exit $rv
fi
